package com.itheima.test;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.UUID;

// 任务类
public class ServerThread implements Runnable {
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // InetAddress inetAddress = null;
        try {
            // 3 获取网络中的字节输入流
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            // 4 创建本地的字节输出流
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/Users/yangqixuan/Documents/develop/Server/" + UUID.randomUUID() + ".jpg"));
            // 5 把接收到的数据保存到本地文件中
            byte[] bys = new byte[1024];
            int len;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
            }

            // 通过客户端Socket对象获取客户端的信息
            SocketAddress socketAddress = socket.getRemoteSocketAddress();
            System.out.println(socketAddress);

            // 本地流关闭
            bos.close();
            // 6 给客户端反馈数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("很好看,谢谢你");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
